var gizwitsws;
var dtype;

var kv1 = new Map();
var kv2 = new Map();
var kvd = new Map();

function newObj(dp) {
	if (gizwitsws != null) {
		mui.alert("对象已被初始化，如需改变参数，请刷新页面.", "提示")
		return;
	}
	var apiHost = "api.gizwits.com";
	var commType = "attrs_v4";
	var wechatOpenId = "13809734334";
	var gizwitsAppId = "7504c477fa0141d6a9f1df82f9202c22";
	gizwitsws = new GizwitsWS(apiHost, wechatOpenId, gizwitsAppId, commType);

	gizwitsws.onInit = onInit;
	gizwitsws.onConnected = onConnected;
	gizwitsws.onOnlineStatusChanged = onOnlineStatusChanged;
	gizwitsws.onReceivedRaw = onReceivedRaw;
	gizwitsws.onReceivedAttrs = onReceivedAttrs;
	gizwitsws.onError = onError;

	dtype = dp;
	initView();
	init();
}

function initView() {
	$.getJSON("uid-考勤机.json", function(data) {
		//data 代表读取到的json中的数据
		console.log(data);
		$.each(data, function(infoIndex, info) {
			console.log('kv1: '+info['uid'].toLowerCase());
			kv1.set(info['uid'].toLowerCase(), info['name']);
		})
	});
	
	$.getJSON("uid-流水线.json", function(data) {
		//data 代表读取到的json中的数据
		console.log(data);
		$.each(data, function(infoIndex, info) {
			console.log('kv2: '+info['uid'].toLowerCase());
			kv2.set(info['uid'].toLowerCase(), info['name']);
		})
	});

	$.getJSON("did.json", function(data) {
		//data 代表读取到的json中的数据
		console.log(data);
		$.each(data, function(infoIndex, info) {
			if(info[Object.keys(info)[0]]['dtype'] == dtype) {
                kvd.set(Object.keys(info)[0].toLowerCase(), info[Object.keys(info)[0]]['name']);
			}
		})
	});
}

function init() {
	gizwitsws.init();
	conndids = [];
}

function connect(did) {
	gizwitsws.connect(did);
}

//=========================================================
// callback functions
//=========================================================
function onInit(devices) {
	if (devices.length == 0) {
		mui.alert("没有绑定的设备", "提示");
	} else {
		for (var i = 0; i < devices.length; i++) {
			console.log('绑定设备：'+devices[i].did);
			switch (dtype) {
				case 1: //考勤机
					//if (devices[i].did == "XIoin4sGcZmeYvwEMFRNtp" ||
					//	devices[i].did == "u19mdlob4bRo9rju8mceoc" ||
					//	devices[i].did == "YiUNyn4T28hyBBv8cDwyRZ") {
					//	connect(devices[i].did);
					//}
					if(kvd.get(devices[i].did.toLowerCase()) != null) {
                        connect(devices[i].did);
					}
					break;

				case 2: //流水线
					//if (devices[i].did == "2Dzm5EKyiQGHxw1UpoqbS9" ||
					//	devices[i].did == "uYgOhwi4Hz7PSGayaP4ZsW" ||
					//	devices[i].did == "XbtKz58k7brwRYhRKCkcTU") {
					//	connect(devices[i].did);
					//}
					if(kvd.get(devices[i].did.toLowerCase()) != null) {
                        connect(devices[i].did);
					}
					break;
			}
		}
	}
}

function onConnected(did) {
	console.log("与设备:" + did + "连接成功!");

	//switch (did) {
	//	case "XIoin4sGcZmeYvwEMFRNtp": //考勤机1
	//		mui.toast("考勤机1连接成功");
	//		break;

	//	case "u19mdlob4bRo9rju8mceoc": //考勤机2
	//		mui.toast("考勤机2连接成功");
	//		break;

	//	case "YiUNyn4T28hyBBv8cDwyRZ": //考勤机测试
	//		mui.toast("考勤机测试连接成功");
	//		break;

	//	case "2Dzm5EKyiQGHxw1UpoqbS9": //流水线1
	//		mui.toast("流水线1连接成功");
	//		break;

	//	case "uYgOhwi4Hz7PSGayaP4ZsW": //流水线2
	//		mui.toast("流水线2连接成功");
	//		break;

	//	case "XbtKz58k7brwRYhRKCkcTU": //流水线测试
	//		mui.toast("流水线测试连接成功");
	//		break;
	//}
    
	mui.toast(kvd.get(did.toLowerCase())+"连接成功");
}

function onOnlineStatusChanged(value) {
	console.log("设备上下线通知，did=" + value.did);
	console.log("设备上下线通知，is_online=" + value.is_online);
}

function onReceivedRaw(value) {
	var str = "收到设备" + value.did + "的Raw: [";
	for (var i = 0; i < value.raw.length; i++) {
		str = str + value.raw[i] + ",";
	}
	str = str.substr(0, str.length - 1) + "]";
	console.log(str);
}

function onReceivedAttrs(value) {
	var str = "收到设备" + value.did + "的Attrs: ";
	for (var key in value.attrs) {
		str = str + key + ":" + value.attrs[key] + "; ";
		showUid(value.did, key, value.attrs[key]);
	}
	console.log(str);
}

function onError(value) {
	console.log(value.toString());
}

//=========================================================
// inner functions
//=========================================================
function showUid(did, k, v) {
	var uid = "";
	for (let i in v) {
		var a = v[i].toString(16);
		if (a.length == 1) {
			a = "0" + a;
		}
		uid = uid + a;
	}
	console.log(uid);
	uid = uid.toLowerCase();
	//switch (did) {
	//	case "XIoin4sGcZmeYvwEMFRNtp": //考勤机1
	//		addUid1(1, uid);
	//		break;

	//	case "u19mdlob4bRo9rju8mceoc": //考勤机2
	//		addUid1(2, uid);
	//		break;

	//	case "2Dzm5EKyiQGHxw1UpoqbS9": //流水线1
	//		addUid2(1, uid);
	//		break;

	//	case "uYgOhwi4Hz7PSGayaP4ZsW": //流水线2
	//		addUid2(2, uid);
	//		break;

	//	case "YiUNyn4T28hyBBv8cDwyRZ": //考勤机测试
	//		addUid1(3, uid);
	//		break;
	//	case "XbtKz58k7brwRYhRKCkcTU": //流水线测试
	//		addUid2(3, uid);
	//		break;
	//}

	addUid(kvd.get(did.toLowerCase()), uid);
}

function addUid(idval, uid) {
	var li = document.createElement("li");
	li.setAttribute("class", "mui-table-view-cell");

	var div = document.createElement("div");
	div.setAttribute("class", "row");
	li.appendChild(div);

	var div1 = document.createElement("div");
	div1.setAttribute("class", "col-xs-3");
	div1.innerHTML = idval != null ? idval : '未知';;
	div.appendChild(div1);

	var div2 = document.createElement("div");
	div2.setAttribute("class", "col-xs-3");

	var uidval;
	if(kv1.get(uid) != null) {
        uidval = kv1.get(uid);
	} else if(kv2.get(uid) != null) {
        uidval = kv2.get(uid);
	}
	div2.innerHTML = uidval != null ? uidval : '未知';
	div.appendChild(div2);

	var div3 = document.createElement("div");
	div3.setAttribute("class", "col-xs-6");
	div3.innerHTML = new Date().Format("yyyy-MM-dd HH:mm:ss");
	div.appendChild(div3);

	if(dtype == 1) {
		document.getElementById("ul_1").prepend(li);
	} else if(dtype == 2) {
		document.getElementById("ul_2").prepend(li);
	}
}

function addUid1(id, uid) {
	var li = document.createElement("li");
	li.setAttribute("class", "mui-table-view-cell");

	var div = document.createElement("div");
	div.setAttribute("class", "row");
	li.appendChild(div);

	var div1 = document.createElement("div");
	div1.setAttribute("class", "col-xs-3");
	div1.innerHTML = "考勤机#" + id;
	div.appendChild(div1);

	var div2 = document.createElement("div");
	div2.setAttribute("class", "col-xs-3");
	div2.innerHTML = kv1.get(uid) != null ? kv1.get(uid) : '未知';
	div.appendChild(div2);

	var div3 = document.createElement("div");
	div3.setAttribute("class", "col-xs-6");
	div3.innerHTML = new Date().Format("yyyy-MM-dd HH:mm:ss");
	div.appendChild(div3);

	document.getElementById("ul_1").prepend(li);
}

function addUid2(id, uid) {
	var li = document.createElement("li");
	li.setAttribute("class", "mui-table-view-cell");

	var div = document.createElement("div");
	div.setAttribute("class", "row");
	li.appendChild(div);

	var div1 = document.createElement("div");
	div1.setAttribute("class", "col-xs-3");
	div1.innerHTML = "流水线#" + id;
	div.appendChild(div1);

	var div2 = document.createElement("div");
	div2.setAttribute("class", "col-xs-3");
	div2.innerHTML = kv2.get(uid) != null ? kv2.get(uid) : '未知';
	div.appendChild(div2);

	var div3 = document.createElement("div");
	div3.setAttribute("class", "col-xs-6");
	div3.innerHTML = new Date().Format("yyyy-MM-dd HH:mm:ss");
	div.appendChild(div3);

	document.getElementById("ul_2").prepend(li);
}

Date.prototype.Format = function(fmt) {
	var o = {
		"M+": this.getMonth() + 1, //月份 
		"d+": this.getDate(), //日 
		"H+": this.getHours(), //小时 
		"m+": this.getMinutes(), //分 
		"s+": this.getSeconds(), //秒 
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度 
		"S": this.getMilliseconds() //毫秒 
	};
	if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
		if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : ((
			"00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}
